package com.detection.controller;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.detection.common.config.DetectionConfig;
import com.detection.common.domain.SysUser;
import com.detection.dahua.demo.oss.PicDownloadDemo;
import com.detection.dahua.model.accesscontrol.record.QueryRecordResponse;
import com.detection.hikvision.config.CusArtemisConfig;
import com.detection.hikvision.domain.EventVo;
import com.detection.hikvision.domain.HaikangReceiveDataVo;
import com.detection.hikvision.domain.YqAccessControlEvent;
import com.detection.hikvision.utils.ArtemisApi;
import com.detection.hikvision.utils.HaiKangHttpUtils;
import com.detection.tcp.client.NettyTcpClient;
import com.detection.tcp.domain.TCPMessage;
import com.detection.tcp.utils.DockingUtils;
import com.detection.yolo.constant.Constants;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author LH
 * @date 2022/10/21 14:39
 */
@Api(tags = "门禁事件处理")
@RestController
@Slf4j
@RequestMapping("scp/accessControlEvent")
public class YqAccessControlEventController {

    @Resource
    private CusArtemisConfig cusArtemisConfig;
    @Autowired
    private NettyTcpClient nettyTcpClient;
    @Autowired
    private PicDownloadDemo picDownloadDemo;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * 门禁人脸进入出入，指纹出入
     *
     * @return
     */
    @RequestMapping("receiveAccessControlEvent")
    public JSONObject receiveCameraEvent(@RequestBody HaikangReceiveDataVo vo) {

        try {
            if (null != vo && !vo.getParams().getEvents().isEmpty()) {

                for (EventVo event : vo.getParams().getEvents()) {
                    LinkedHashMap dataMap = (LinkedHashMap) event.getData();

                    String evenType = getEventType(event);
                    if (!Objects.isNull(evenType)) {
                        Map<String, Object> map = getYqAccessControlEvent(event, evenType, dataMap);
                        YqAccessControlEvent yqAccessControlEvent = (YqAccessControlEvent) map.get("yqAccessControlEvent");

//                        map.put("picUrl", yqAccessControlEvent.getPicUrl() == null ? "" : "https://" + haikangIp + yqAccessControlEvent.getPicUrl());
                        QueryRecordResponse.Data.PageData pageData = new QueryRecordResponse.Data.PageData();

                        pageData.setSwingTime(yqAccessControlEvent.getHappenTime());
                        pageData.setPersonName(yqAccessControlEvent.getPersonName());
                        if(Objects.isNull(yqAccessControlEvent.getInOut())){
                            yqAccessControlEvent.setInOut("0");
                        }
                        pageData.setEnterOrExit(Integer.parseInt(yqAccessControlEvent.getInOut()));
                        pageData.setDeviceName(yqAccessControlEvent.getSrcName());

                        pageData.setOpenType(event.getEventType());
                        pageData.setPaperNumber(yqAccessControlEvent.getIdCard());
                        pageData.setHkPersonId(yqAccessControlEvent.getPersonId());
                        if(Objects.nonNull(yqAccessControlEvent.getPicUrl())){

                            String host = cusArtemisConfig.getHost();
                            String haikangIp = host.split(":")[0];
                            pageData.setRecordImageUrl("https://" + haikangIp + pageData.getRecordImageUrl());
                            String destPath =  "/dahuaaccess/"+ cn.hutool.core.date.DateUtil.format(new Date(),"yyyy-MM-dd");
                            File destPathFile = new File(DetectionConfig.getProfile()+destPath);
                            if(!destPathFile.exists()){
                                destPathFile.mkdirs();
                            }
                            String url2 = UUID.randomUUID().toString(true)+".png";
                            picDownloadDemo.downloadHaiKang(pageData.getRecordImageUrl(),DetectionConfig.getProfile()+destPath+"/"+url2);
                            pageData.setRecordImageUrl(DetectionConfig.getSendAddress()+ Constants.RESOURCE_PREFIX+destPath + "/" + url2);
                        }
                        List<QueryRecordResponse.Data.PageData> subList = new ArrayList<>();
                        TCPMessage message = new TCPMessage();
                        message.setId("12");
                        message.setFlag("updateAccessControl");
                        message.setData(subList);
                        message.setCampCode(DetectionConfig.getCampCode());
                        nettyTcpClient.sendMessage(message);
                        DockingUtils.postForTCP(message);
                    }

                }

            }
            JSONObject object = new JSONObject();
            object.put("code", 0);
            object.put("msg", "success");
            return object;
        } catch (Exception e) {
            JSONObject object = new JSONObject();
            object.put("code", 0);
            object.put("msg", "");
            throw new RuntimeException(e);
        }


    }




    /**
     * 获取YqAccessControlEvent对象
     *
     * @param event
     * @param evenType
     * @param dataMap
     * @return
     */
    private Map<String, Object> getYqAccessControlEvent(EventVo event, String evenType, LinkedHashMap dataMap) {
        YqAccessControlEvent event1 = new YqAccessControlEvent();
        event1.setEvenType(evenType);
        String personId = dataMap.get("ExtEventPersonNo").toString();
        int ExtEventInOut = (int) dataMap.get("ExtEventInOut");
        String inOut = null;
        if (ExtEventInOut == 1) {
//            inOut = "0";
            inOut = "1";//之前是“0”，根据反馈核对修改
        } else {
//            inOut = "1";
            inOut = "0";
        }
        HaiKangHttpUtils haiKangHttpUtils = new HaiKangHttpUtils();

        Map<String, Object> map = new HashMap<>();
        event1.setPersonType("内部人员");

        map = setPersonModo(personId, haiKangHttpUtils, event1);

        event1 = (YqAccessControlEvent) map.get("yqAccessControlEvent");

        event1.setEvenTypeCode(String.valueOf(event.getEventType()));
        Object picUrl = dataMap.get("ExtEventPictureURL");
        event1.setPicUrl(null != picUrl ? picUrl.toString() : null);
        Object svrIndexCode = dataMap.get("svrIndexCode");
        event1.setSvrIndexCode(null != svrIndexCode ? svrIndexCode.toString() : null);
        event1.setInOut(inOut);
        event1.setHappenTime(sdf.format(DateUtil.parseDatetime(event.getHappenTime())));
        event1.setPersonId(personId);
        event1.setSrcName(event.getSrcName());
        event1 = getResourceDoor(event, haiKangHttpUtils, event1);
        map.put("yqAccessControlEvent", event1);
        return map;
    }

    /**
     * 获取门禁点软件
     *
     * @param event
     * @param haiKangHttpUtils
     * @param event1
     * @return
     */
    private YqAccessControlEvent getResourceDoor(EventVo event, HaiKangHttpUtils haiKangHttpUtils, YqAccessControlEvent event1) {
        //获取门禁点列表
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 1000);
        jsonBody.put("name", event.getSrcName());
        String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_RESOURCE_DOOR_LIST);
        JSONObject result = JSON.parseObject(send);
        JSONObject data = result.getJSONObject("data");
        JSONArray jsonArray = data.getJSONArray("list");
        int size = jsonArray.size();
        for (int i = 0; i < size; i++) {
            JSONObject oneObj = jsonArray.getJSONObject(i);
            if (event.getSrcName().equals(oneObj.getString("name"))) {
                event1.setSrcIndex(event.getSrcIndex());
                String regionPath = oneObj.getString("regionPath");
                String[] zRegions = regionPath.split("@");
                if (zRegions.length > 3) {
                    event1.setParkRegionIndex(zRegions[3]);
                    //存储所属区域路径和区域路径名
                    event1.setRegionPath(regionPath);
                    event1.setRegionPathName(oneObj.getString("regionPathName"));
                }
                break;
            }
        }
        return event1;
    }

    /**
     * 设置固定客户model
     *
     * @param haiKangHttpUtils
     * @param event1
     * @return
     */
    private Map<String, Object> setPersonModo(String personId, HaiKangHttpUtils haiKangHttpUtils, YqAccessControlEvent event1) {
        Map<String, Object> map = new HashMap<>(16);

        SysUser user = null;
        event1.setPersonType("陌生人");
        if (!"".equals(personId)) {
            JSONObject jsonBody = new JSONObject();
            //内部用户
            jsonBody.put("personIds", personId);
            jsonBody.put("pageNo", 1);
            jsonBody.put("pageSize", 1000);
            String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_PERSONLIST);

            JSONObject result = JSON.parseObject(send);
            JSONObject data = result.getJSONObject("data");
            JSONArray jsonArray = data.getJSONArray("list");

            if (jsonArray.size() > 0) {
                String personName = jsonArray.getJSONObject(0).getString("personName");
                event1.setPersonName(personName);
                //性别，1：男；2：女；0：未知
                Integer gender = jsonArray.getJSONObject(0).getInteger("gender");
                event1.setGender(String.valueOf(gender));
                String idCard = jsonArray.getJSONObject(0).getString("certificateNo");
                event1.setIdCard(idCard);
            }
        }
        map.put("yqAccessControlEvent", event1);
        return map;
    }



    /**
     * 获取evenType
     *
     * @param event
     * @return
     */
    private String getEventType(EventVo event) {
        String evenType = null;
        switch (event.getEventType()) {
            // 人脸认证通过
            case 196893:
                evenType = "人像刷门";
                break;
            //人脸认证失败
            case 197151:
            case 197160:
                evenType = "人像非法刷门";
                break;
            //指纹认证通过
            case 197127:
                evenType = "合法指纹开门";
                break;
            //指纹认证失败
            case 197128:
                evenType = "指纹认证失败";
                break;
            //指纹不存在
            case 197140:
                evenType = "指纹不存在";
                break;
            //合法卡比对通过  访客人员
            case 198914:
                evenType = "合法卡比对通过";
                break;
            case 199710:
                evenType = "设备离线";
                break;
        }
        return evenType;
    }

}
